package com.huanshi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanshi.common.CommonResult;
import com.huanshi.entity.UmsAdmin;
import com.huanshi.mapper.UmsAdminMapper;
import com.huanshi.module.ums.param.LoginParam;
import com.huanshi.module.ums.param.PasswordParam;
import com.huanshi.service.UmsAdminService;
import com.huanshi.utils.JwtTokenUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author 幻世
 * @since 2023-09-13
 */
@Service
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements UmsAdminService {

    @Resource
    private UmsAdminMapper adminMapper;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UmsAdmin findByEmail(String email) {
        return adminMapper.selectOne(
                new LambdaQueryWrapper<UmsAdmin>()
                        .eq(UmsAdmin::getEmail, email)
        );
    }

    @Override
    public UmsAdmin findByName(String username) {
        return adminMapper.selectOne(
                new LambdaQueryWrapper<UmsAdmin>()
                        .eq(UmsAdmin::getUserName, username)
        );
    }

    @Override
    public CommonResult login(LoginParam loginParam) {
        var user = adminMapper.selectOne(new LambdaQueryWrapper<UmsAdmin>()
                .eq(UmsAdmin::getUsername, loginParam.getUserName())
        );
        if (user == null || !passwordEncoder.matches(loginParam.getPassword(), user.getPassword())){
            return CommonResult.failed("用户名或密码不正确！");
        }

        var jwtToken = JwtTokenUtil.createJWT(user.getUserId(), user.getUserName(),new ArrayList<>());

        return CommonResult.success(jwtToken, "认证成功！");

    }

    @Override
    public UmsAdmin getUserInfo(String token) {
        Integer userId = JwtTokenUtil.getUserId(token);
        return adminMapper.selectOne(
                new LambdaQueryWrapper<UmsAdmin>()
                        .eq(UmsAdmin::getUserId, userId));
    }

    @Override
    public CommonResult updatePassword(PasswordParam passwordParam) {
        LambdaUpdateWrapper<UmsAdmin> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UmsAdmin::getUserName, passwordParam.getUserName());
        updateWrapper.set(UmsAdmin::getPassword, passwordEncoder.encode(passwordParam.getNewPassword()));
        int update = adminMapper.update(null, updateWrapper);
        if (update >= 1) {
            return CommonResult.success(update);
        } else {
            return CommonResult.failed("更新密码失败");
        }
    }
}
